package com.hmall.trade.listener;

import cn.hutool.core.bean.BeanUtil;
import com.hmall.api.client.ItemClient;
import com.hmall.api.client.PayClient;
import com.hmall.api.dto.OrderDetailDTO;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.domain.po.OrderDetail;
import com.hmall.trade.service.IOrderDetailService;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class OrderDelayMessageListener {

    private final IOrderService orderService;
    private final ItemClient itemClient;
    private final IOrderDetailService orderDetailService;
    private final PayClient payClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "trade.delay.order.queue"),
            exchange = @Exchange(name = "trade.delay.direct", delayed = "true"),
            key = "delay.order.query"
    ))
    public void listenOrderDelayMessage(Long orderId) {
        log.info("订单{}超过支付时间,自动取消", orderId);
        Order order = orderService.getById(orderId);
        if (order != null && order.getStatus() == 1) {
            //1. 修改订单的支付状态
            order.setStatus(5);
            orderService.updateById(order);

            //todo  下面功能自行完成
            //2. 恢复库存 需要远程调用item微服务
            //2.1 查询下单商品的数量和id--order_detail中item_id和num
            List<OrderDetail> list = orderDetailService.lambdaQuery()
                    .select(OrderDetail::getItemId, OrderDetail::getNum)
                    .eq(OrderDetail::getOrderId, orderId)
                    .list();
            //2.2将list拷贝到OrderDetailDTO
            List<OrderDetailDTO> orderDetailDTOS = BeanUtil.copyToList(list, OrderDetailDTO.class);
            itemClient.addStock(orderDetailDTOS);

            //3. 修改支付状态状态 需要远程调用pay微服务
            payClient.upload(orderId);
        }
    }
}